package vn.egame.elockscreen.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;

import android.content.Context;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;
import egame.libs.zipfile.ZipResourceFile;

/**
 * Created by Administrator on 2014/7/22.
 */
public class Constans {
	public static final String START_SCREEN_SAVER_TYPE = "start_screen_saver_type";

	public static final String CUSTOM_LAUNCHER_PACKAGE = "custom_launcher_package";
	public static final String CUSTOM_LAUNCHER_NAME = "custom_launcher_name";

	public static final String IS_LOCK_ENABLED = "is_lock_enabled";

	public static final int IS_HOME_BLOCKED = 1;

	public enum StartScreenSaverType {
		INIT_SETTING(1), PRESS_HOME(2), SCREEN_OFF(3);

		private int value;

		private StartScreenSaverType(int i) {
			this.value = i;
		}

		public int getValue() {
			return this.value;
		}
	}

	public static Bitmap getBtimapFromZip(final String zipFilePath,
			final String imageFileInZip) {

		Bitmap result = null;
		try {
			FileInputStream fis = new FileInputStream(zipFilePath);
			ZipInputStream zis = new ZipInputStream(fis);
			ZipEntry ze = null;
			while ((ze = zis.getNextEntry()) != null) {
				if (ze.getName().equals(imageFileInZip)) {
					result = BitmapFactory.decodeStream(zis);
					fis.close();
					fis = null;
					break;
				}
			}
		} catch (FileNotFoundException e) {
			Log.e("kai",
					"Extracting file: Error opening zip file - FileNotFoundException: ",
					e);
			e.printStackTrace();
		} catch (IOException e) {
			Log.e("kai",
					"Extracting file: Error opening zip file - IOException: ",
					e);
			e.printStackTrace();
		}
		return result;
	}

	public static String parseJsonFromZip(final String zipFilePath,
			final String jsonFileInZip) {

		File file = new File(zipFilePath);
		try {
			ZipFile zipfile = new ZipFile(file);

			ZipEntry zipentry;

			// Log.d("Kai", "nList of files in zip archive");
			// int fileNumber = 0;
			// for (Enumeration<? extends ZipEntry> e = zipfile.entries(); e
			// .hasMoreElements(); fileNumber++) {
			// zipentry = e.nextElement();
			//
			// if (!zipentry.isDirectory()) {
			// Log.d("Kai", fileNumber + "-" + zipentry.getName());
			// }
			// }

			for (Enumeration<? extends ZipEntry> e = zipfile.entries(); e
					.hasMoreElements();) {
				zipentry = e.nextElement();

				if (!zipentry.isDirectory()
						&& zipentry.getName().equals(jsonFileInZip)) {
					InputStream inputstream = zipfile.getInputStream(zipentry);
					String str = new java.util.Scanner(inputstream)
							.useDelimiter("\\A").next();
					Log.d("Kai", "value in scanner str:" + str);
					return str;
				}
			}
		} catch (ZipException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return null;
	}

	public static void close(InputStream mInputStream) throws IOException {
		if (mInputStream != null) {
			mInputStream.close();
			mInputStream = null;
		}
	}

	public static Drawable loadResourceEV(Context context, String path,
			String name) {
		final Resources mResources = context.getResources();

		// File file = Environment.getExternalStorageDirectory();
		// File mFile = new File(file.getAbsolutePath()
		// + File.separator + path);

		final File mFile = new File(path);
		if (!mFile.exists()) {
			Toast.makeText(context, "Not exit", 1000).show();
			return null;

		}
		try {
			ZipResourceFile expansionFile = new ZipResourceFile(
					mFile.getAbsolutePath());
			Log.d("Kai", mFile.getAbsolutePath());
			InputStream mInputStream;
			mInputStream = expansionFile.getInputStream("/" + name + ".png");
			Bitmap result = BitmapFactory.decodeStream(mInputStream);
			close(mInputStream);
			Log.d("Kai", "close");
			if (result != null) {
				Drawable icon = new BitmapDrawable(mResources, result);
				Log.d("Kai", "icon");
				return icon;
			}
		} catch (Exception e) {
			Log.d("Kai", "Exception");
		}

		Toast.makeText(context, "Null", 1000).show();
		return null;
	}

	public static Bitmap getBitmapFromAsset(Context context, String filePath) {
		AssetManager assetManager = context.getAssets();

		InputStream istr;
		Bitmap bitmap = null;
		try {
			istr = assetManager.open(filePath);
			bitmap = BitmapFactory.decodeStream(istr);
		} catch (IOException e) {
			// handle exception
		}

		return bitmap;
	}

	// kai
	// private static void loadConfigureEV(Context context, ThemesElement info){
	// final File mFile = new File(info.getFileName());
	// if(!mFile.exists()) return;
	// try {
	// ZipResourceFile expansionFile = new
	// ZipResourceFile(mFile.getAbsolutePath());
	// XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
	// factory.setNamespaceAware(true);
	// XmlPullParser xpp = factory.newPullParser();
	// InputStream mInputStream = expansionFile.getInputStream("media.xml");
	// InputStreamReader reader = new InputStreamReader(mInputStream);
	// xpp.setInput(reader);
	// int eventType = xpp.getEventType();
	// while (eventType != XmlPullParser.END_DOCUMENT) {
	// if (eventType == XmlPullParser.START_TAG
	// && xpp.getName().equals("devicetheme")) {
	// float scale = Float.parseFloat(xpp
	// .getAttributeValue(null, "Scale"));
	// float YOffset = Float.parseFloat(xpp
	// .getAttributeValue(null, "YOffsetPCT"));
	// float XOffset = Float.parseFloat(xpp
	// .getAttributeValue(null, "XOffsetPCT"));
	// ThemeUtils.putConfig(ThemeUtils.ICON_SCALE, scale);
	// ThemeUtils.putConfig(ThemeUtils.ICON_XOFFSET, XOffset);
	// ThemeUtils.putConfig(ThemeUtils.ICON_YOFFSET, YOffset);
	// break;
	// }
	// eventType = xpp.next();
	// }
	// mInputStream.close();
	// reader.close();
	// } catch (Exception e) {
	// }
	// }

	public static Bitmap loadBitmap(Context context, int resouce) {
		return BitmapFactory.decodeResource(context.getResources(), resouce);
	}

	public static Bitmap loadBitmapFromSdcard(String photoPath) {
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inPreferredConfig = Bitmap.Config.ARGB_8888;
		return BitmapFactory.decodeFile("/sdcard/" + photoPath, options);
	}

	public static String readColumn(String path) {
		String state = Environment.getExternalStorageState();
		StringBuilder textBuilder = new StringBuilder();
		if (!(state.equals(Environment.MEDIA_MOUNTED))) {
			// Toast.makeText(this, "There is no any sd card",
			// Toast.LENGTH_LONG)
			// .show();

		} else {
			BufferedReader reader = null;
			try {
				// Toast.makeText(this, "Sd card available", Toast.LENGTH_LONG)
				// .show();
				File file = Environment.getExternalStorageDirectory();
				File textFile = new File(file.getAbsolutePath()
						+ File.separator + path + "config.txt");
				reader = new BufferedReader(new FileReader(textFile));

				String line;
				while ((line = reader.readLine()) != null) {
					textBuilder.append(line);
					textBuilder.append("\n");

				}

			} catch (FileNotFoundException e) {
				// TODO: handle exception
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} finally {
				if (reader != null) {
					try {
						reader.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}

		}
		return textBuilder.toString();
	}

	public static int calculateInSampleSize(BitmapFactory.Options options,
			int reqWidth, int reqHeight) {
		// Raw height and width of image
		final int height = options.outHeight;
		final int width = options.outWidth;
		int inSampleSize = 1;

		if (height > reqHeight || width > reqWidth) {

			final int halfHeight = height / 2;
			final int halfWidth = width / 2;

			// Calculate the largest inSampleSize value that is a power of 2 and
			// keeps both
			// height and width larger than the requested height and width.
			while ((halfHeight / inSampleSize) > reqHeight
					&& (halfWidth / inSampleSize) > reqWidth) {
				inSampleSize *= 2;
			}
		}

		return inSampleSize;
	}
	
	public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
	        int reqWidth, int reqHeight) {

	    // First decode with inJustDecodeBounds=true to check dimensions
	    final BitmapFactory.Options options = new BitmapFactory.Options();
	    options.inJustDecodeBounds = true;
	    BitmapFactory.decodeResource(res, resId, options);

	    // Calculate inSampleSize
	    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

	    // Decode bitmap with inSampleSize set
	    options.inJustDecodeBounds = false;
	    return BitmapFactory.decodeResource(res, resId, options);
	}
}
